package com.qigao.mall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qigao.mall.api.*;
import com.qigao.mall.commons.dto.*;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.commons.po.DivideAppyPo;
import com.qigao.mall.commons.po.DivideDetailPo;
import com.qigao.mall.commons.utils.DateUtil;
import com.qigao.mall.commons.utils.IDUtils;
import com.qigao.mall.jdbc.mapper.*;
import com.qigao.mall.jdbc.model.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020
 * FileName: PromGroupServiceImpl
 * Author:   luiz
 * Date:     2020/10/15 14:37
 * Description: 团购实现类
 */
@Service
public class PromGroupServiceImpl implements PromGroupService {
    private static final Logger logger= LoggerFactory.getLogger(PromGroupServiceImpl.class);
    @Resource
    private PromGroupMapper promGroupMapper;
    @Resource
    private PromGroupDetailMapper promGroupDetailMapper;
    @Resource
    private TbItemMapper tbItemMapper;
    @Resource
    private TbItemSkuMapper tbItemSkuMapper;
    @Resource
    private RefundService refundService;
    @Resource
    private ProfitDetailService profitDetailService;
    @Resource
    private AccountInfoService accountInfoService;
    @Resource
    private AccountSerivce accountSerivce;
    @Resource
    DataSourceTransactionManager transactionManager;
    @Resource
    SysDictService sysDictService;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public Result<String> create(PromGroupCreateDto promGroupCreateDto) {
        SysUser sysUser=sysUserMapper.selectByUserNo(promGroupCreateDto.getOperUserNo());
        if(UserTypeEnum.CUSTOMER.getCode()!=sysUser.getUserType()){
            logger.error("{}非团长，不能创建",promGroupCreateDto.getOperUserNo());
            return Result.newError(ResultCode.PROM_NOT_LEADER);
        }
        //判断是否存在有效的团购
        PromGroup promGroupOld=promGroupMapper.selectOneByIndex(promGroupCreateDto.getItemNo(),promGroupCreateDto.getOperUserNo());
        if(promGroupOld!=null){
            Date nowTime1=new Date();
            int actNum=promGroupOld.getActNum();
            int targetNum=promGroupOld.getTargetNum();
            if(nowTime1.before(promGroupOld.getEndTime())&&actNum!=targetNum){
                logger.error("商品{}已存在有效团购并且尚未满员，不能创建{}",promGroupCreateDto.getItemNo(),promGroupCreateDto.getOperUserNo());
                return Result.newError(ResultCode.PROM_HAS_EXISTS);
            }else {

            }
        }
        PromGroup promGroup=new PromGroup();
        String groupNo=IDUtils.genIdStr(IdTypeEnum.PROM_GROUP);
        promGroup.setGroupNo(groupNo);
        promGroup.setItemNo(promGroupCreateDto.getItemNo());
        TbItem tbItem=tbItemMapper.selectByItemNo(promGroupCreateDto.getItemNo());
        promGroup.setItemTitle(tbItem.getItemTitle());
        String targetNum=sysDictService.findByUniq(DictTypeEnum.PROM_GROUP.getCode(),"TARGET_NUM");
        promGroup.setTargetNum(Integer.valueOf(targetNum));
        promGroup.setActNum(0);
        promGroup.setMerNo(promGroupCreateDto.getMerNo());
        promGroup.setShopNo(promGroupCreateDto.getShopNo());
        promGroup.setLeaderUser(promGroupCreateDto.getOperUserNo());
        // 团长分润比例 根据商品来设置分润比例
        //String returnPercent=sysDictService.findByUniq(DictTypeEnum.PROM_GROUP.getCode(),"LEADER_PERCENT");
        //promGroup.setReturnRate(new BigDecimal(returnPercent));
        Date nowTime=new Date();
        promGroup.setStartTime(nowTime);
        promGroup.setGroupStatus(GroupStatusEnum.PROCESS.getCode());
        String overMinute=sysDictService.findByUniq(DictTypeEnum.PROM_GROUP.getCode(),"OVER_MINUTE");
        promGroup.setEndTime(DateUtil.addMinute(nowTime,Integer.valueOf(overMinute)));
        promGroup.setCreateNo(promGroupCreateDto.getOperUserNo());
        promGroup.setCreateTime(nowTime);
        promGroupMapper.insertSelective(promGroup);
        return Result.newSuccess(groupNo);
    }

    @Override
    public Result<List<PromGroupResultDto>> findByItemNo(String itemNo) {
        //使用PageHelper类进行分页
        PageHelper.startPage(0, 5);
        List<PromGroup> promGroups = promGroupMapper.selectValidByItemNo(itemNo);
        if(CollectionUtils.isEmpty(promGroups)){
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        List<PromGroupResultDto> promGroupResultDtos=new ArrayList<>();
        for(PromGroup promGroup:promGroups){
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            promGroupResultDtos.add(promGroupResultDto);
        }
        return Result.newSuccess(promGroupResultDtos);
    }

    private PromGroupResultDto buildGroupResult(PromGroup promGroup) {
        PromGroupResultDto promGroupResultDto=new PromGroupResultDto();
        BeanUtils.copyProperties(promGroup,promGroupResultDto);
        promGroupResultDto.setStartTime(DateUtil.getDateTimeFormat(promGroup.getStartTime()));
        promGroupResultDto.setEndTime(DateUtil.getDateTimeFormat(promGroup.getEndTime()));
        promGroupResultDto.setFullTime(DateUtil.getDateTimeFormat(promGroup.getFullTime()));
        promGroupResultDto.setSettleTime(DateUtil.getDateTimeFormat(promGroup.getSettleTime()));
        SysUser sysUser=sysUserMapper.selectByUserNo(promGroup.getLeaderUser());
        if(sysUser!=null){
            promGroupResultDto.setLeaderUserHeadUrl(sysUser.getHeadUrl());
            promGroupResultDto.setLeaderNickName(sysUser.getNickName());
        }
        List<PromGroupDetailResultDto> promGroupDetailResultDtos=new ArrayList<PromGroupDetailResultDto>();
        List<PromGroupDetail> promGroupDetails=promGroupDetailMapper.selectByGroupNo(promGroup.getGroupNo());
        for(PromGroupDetail promGroupDetail:promGroupDetails){
            PromGroupDetailResultDto promGroupDetailResultDto=new PromGroupDetailResultDto();
            BeanUtils.copyProperties(promGroupDetail,promGroupDetailResultDto);
            SysUser sysUser1=sysUserMapper.selectByUserNo(promGroupDetail.getBuylerId());
            if(sysUser1!=null){
                promGroupDetailResultDto.setBuylerHeadUrl(sysUser1.getHeadUrl());
                promGroupDetailResultDto.setBuylerNickName(sysUser1.getNickName());
            }
            promGroupDetailResultDto.setSettleTime(DateUtil.getDateTimeFormat(promGroupDetail.getSettleTime()));
            promGroupDetailResultDtos.add(promGroupDetailResultDto);
        }
        promGroupResultDto.setPromGroupDetailResultDtoList(promGroupDetailResultDtos);
        return promGroupResultDto;
    }


    @Override
    public Result<PageInfo<PromGroupResultDto>> listPage(PromGroupCondDto promGroupCondDto) {
        //使用PageHelper类进行分页
        PageHelper.startPage(promGroupCondDto.getPageIndex(), promGroupCondDto.getPageSize());
        Page<PromGroup> promGroupPage = (Page<PromGroup>) promGroupMapper.selectByCond(promGroupCondDto);
        if(CollectionUtils.isEmpty(promGroupPage)){
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        List<PromGroup> promGroups =promGroupPage.getResult();
        Page<PromGroupResultDto> promGroupResultDtoPage=new Page<PromGroupResultDto>();
        BeanUtils.copyProperties(promGroupPage,promGroupResultDtoPage);
        for(PromGroup promGroup:promGroups){
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            promGroupResultDtoPage.add(promGroupResultDto);
        }
        PageInfo pageInfo = new PageInfo(promGroupResultDtoPage);
        return Result.newSuccess(pageInfo);
    }

    @Override
    public List<PromGroupResultDto> findByCond(PromGroupCondDto promGroupCondDto) {
        List<PromGroup> promGroupList =promGroupMapper.selectByCond(promGroupCondDto);
        if(CollectionUtils.isEmpty(promGroupList)){
            return null;
        }
        List<PromGroupResultDto> promGroupResultDtoList=new ArrayList<>();
        for(PromGroup promGroup:promGroupList){
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            promGroupResultDtoList.add(promGroupResultDto);
        }
        return promGroupResultDtoList;
    }

    @Override
    public Result<PromGroupResultDto> findByGroupNo(String groupNo) {
        PromGroup promGroup=promGroupMapper.selectByGroupNo(groupNo);
        if(promGroup==null){
            return Result.newError(ResultCode.PROM_NOT_EXISTS);
        }
        PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
        return Result.newSuccess(promGroupResultDto);
    }

    @Override
    public Result<PageInfo<PromGroupResultDto>> findByItemNoAndGroupNo(String itemNo, String groupNo) {
        //使用PageHelper类进行分页
        PageHelper.startPage(0, 5);
        Page<PromGroup> promGroups = (Page<PromGroup>)promGroupMapper.selectValidByItemNo(itemNo);
        if(CollectionUtils.isEmpty(promGroups)){
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        Page<PromGroupResultDto> promGroupResultDtoPage=new Page<>();
        BeanUtils.copyProperties(promGroups,promGroupResultDtoPage);
        if(!StringUtils.isEmpty(groupNo)){
            PromGroup promGroup= promGroupMapper.selectByGroupNo(groupNo);
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            if(promGroup.getActNum()==promGroup.getTargetNum()||promGroup.getEndTime().before(new Date())){
                //已过期或已经满足条件
                promGroupResultDto.setShowButton("N");
            }else {
                promGroupResultDto.setShowButton("Y");
            }
            promGroupResultDtoPage.add(promGroupResultDto);
        }
        for(PromGroup promGroup:promGroups.getResult()){
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            if(StringUtils.isEmpty(groupNo)){
                promGroupResultDto.setShowButton("Y");
            }
            //去除重复
            if(!promGroup.getGroupNo().equals(groupNo)){
                promGroupResultDtoPage.add(promGroupResultDto);
            }
        }
        return Result.newSuccess(new PageInfo<PromGroupResultDto>(promGroupResultDtoPage));
    }

    @Override
    public List<PromGroupResultDto> selectByOrderNos(List<String> orderNos) {
        List<PromGroup> promGroups=promGroupMapper.selectByOrderNos(orderNos);
        List<PromGroupResultDto> promGroupResultDtos=new ArrayList<>();
        for(PromGroup promGroup:promGroups){
            PromGroupResultDto promGroupResultDto=buildGroupResult(promGroup);
            promGroupResultDtos.add(promGroupResultDto);
        }
        return promGroupResultDtos;
    }

    @Override
    public PromGroupResultDto selectByOrderNo(String orderNo) {
        PromGroup promGroup=promGroupMapper.selectByOrderNo(orderNo);
        return buildGroupResult(promGroup);
    }

    @Override
    public Result<Boolean> checkJoinGroup(String groupNo, String buylerId) {
        PromGroup promGroup=promGroupMapper.selectByGroupNo(groupNo);
        if(promGroup==null){
            logger.warn("团购{}不存在,不能加入!",groupNo);
            throw new BusinessException(ResultCode.PROM_NOT_EXISTS);
        }
        Date nowTime1=new Date();
        int actNum=promGroup.getActNum();
        int targetNum=promGroup.getTargetNum();
        if(nowTime1.after(promGroup.getEndTime())||actNum==targetNum){
            logger.error("团购{}已失效或者已满员，不能再次创建订单",groupNo);
            throw new BusinessException(ResultCode.PROM_NOT_VALID);
        }
        PromGroupDetail promGroupDetail=promGroupDetailMapper.selectByIndex(groupNo,buylerId);
        if(promGroupDetail!=null){
            logger.warn("{}已经加入团购{}，无需再次创建",buylerId,groupNo);
            throw new BusinessException(ResultCode.PROM_HAS_CREATE);
        }
        return Result.newSuccess(Boolean.TRUE);
    }

    /**
     * 是否允许支付
     * @param orderNo
     * @return
     */
    @Override
    public boolean checkCanPay(String orderNo) {
        PromGroupDetail promGroupDetail=promGroupDetailMapper.selectByOrderNo(orderNo);
        if(promGroupDetail==null){
            logger.warn("非团购订单，可以去支付{}",orderNo);
            return true;
        }
        if(StringUtils.isNotEmpty(promGroupDetail.getPaySeqNo())){
            logger.warn("团购订单,已经支付过，无需再次支付:{}",orderNo);
            return false;
        }
        PromGroup promGroup=promGroupMapper.selectByGroupNo(promGroupDetail.getGroupNo());
        Date nowTime1=new Date();
        int actNum=promGroup.getActNum();
        int targetNum=promGroup.getTargetNum();
        if(nowTime1.after(promGroup.getEndTime())||actNum==targetNum){
            logger.warn("团购{}已失效或者已满员，不能去支付",promGroupDetail.getGroupNo());
            return false;
        }
        return true;
    }

    @Override
    public void payNotify(String paySeqNo,BigDecimal payAmt, String orderNo, String buylerId) {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setName(TransactionTypeEnum.PROM_GROUP_PAY.getCode());
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transactionStatus = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            PromGroupDetail promGroupDetail=promGroupDetailMapper.selectByUserAndOrderNo(buylerId,orderNo);
            if(promGroupDetail==null){
                logger.warn("非团购订单{}，无需处理",orderNo);
                return;
            }
            //1.检查人数是否已满; 已满需要自动发起退款
            PromGroup promGroup=promGroupMapper.selectByGroupNo(promGroupDetail.getGroupNo());
            if(promGroup.getActNum()==promGroup.getTargetNum()){
                //人数已满，发起自动退款 todo
                return;
            }
            if(promGroup.getEndTime().before(new Date())){
                //团购已过期，发起自动退款 todo
                return;
            }
            //3.加入团购成功
            promGroupDetail.setPayAmt(payAmt);
            promGroupDetail.setPaySeqNo(paySeqNo);
            promGroupDetail.setModiTime(new Date());
            promGroupDetailMapper.updateByPrimaryKeySelective(promGroupDetail);
            int actNum=promGroup.getActNum()+1;
            if(actNum==promGroup.getTargetNum()){
                promGroup.setFullTime(new Date());
                promGroup.setGroupStatus(1);
                processSingleGroup(promGroup);
            }
            int saveNum=promGroupMapper.addActNum(promGroup);
            if(saveNum!=1){
                //未更新成功，发起自动退款 todo
                return;
            }
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error("[支付成功团购处理]发生异常:{}",e);
            transactionManager.rollback(transactionStatus);
        }
    }

    /**
     * 随机命中
     * @param promGroup
     */
    private void processSingleGroup(PromGroup promGroup) {
        List<PromGroupDetail> promGroupDetails=promGroupDetailMapper.selectByGroupNo(promGroup.getGroupNo());
        List<PromGroupDetail> resultGroupDetails=promGroupDetails.stream().filter(o->o.getOrderAmt().equals(o.getPayAmt())).collect(Collectors.toList());
        //1.随机命中某个购买人
        int randomIndex= RandomUtils.nextInt(0,resultGroupDetails.size()-1);
        PromGroupDetail promGroupDetail=resultGroupDetails.get(randomIndex);
        promGroupDetail.setHitFlag(1);
        promGroupDetailMapper.updateByPrimaryKeySelective(promGroupDetail);
    }

    /**
     * 自动关闭
     */
    @Override
    public void autoClose() {
        List<PromGroup> promGroups= promGroupMapper.selectOverTime();
        if(CollectionUtils.isEmpty(promGroups)){
            logger.debug("超时团购为空,不能进行关闭操作...");
            return;
        }
        for(PromGroup promGroup:promGroups){
            promGroup.setGroupStatus(GroupStatusEnum.FAIL.getCode());
            promGroup.setModiTime(new Date());
            logger.info("[超时自动关闭]未拼团成功，自动关闭{}",promGroup.getId());
            promGroupMapper.updateByPrimaryKeySelective(promGroup);
        }
    }

    /**
     * 自动退款
     */
    @Override
    public void autoRefund() {
        List<PromGroup> promGroups= promGroupMapper.selectUnRefund();
        if(CollectionUtils.isEmpty(promGroups)){
            logger.debug("待处理团购为空，不能退款...");
            return;
        }
        promGroupMapper.processPromGroup(promGroups);
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setName(TransactionTypeEnum.PROM_GROUP_SETTLE.getCode());
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transactionStatus = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            for(PromGroup promGroup:promGroups){
                logger.info("[超时自动退款]超时未拼团成功，自动退款处理{}",promGroup.getId());
                settleSingleGroup(promGroup);
            }
            promGroupMapper.closePromGroup(promGroups);
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error("自动退款错误:{}",e);
            transactionManager.rollback(transactionStatus);
        }
    }

    /**
     * 开始自动结算
     * 2.未命中发起退款
     * 3.命中的进行分账
     */
    @Override
    public void autoSettle() {
        List<PromGroup> promGroups= promGroupMapper.selectUnSettle();
        if(CollectionUtils.isEmpty(promGroups)){
            logger.debug("待处理团购为空，不能结算....");
            return;
        }
        promGroupMapper.processPromGroup(promGroups);
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setName(TransactionTypeEnum.PROM_GROUP_SETTLE.getCode());
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transactionStatus = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            for(PromGroup promGroup:promGroups){
                logger.info("[超时自动退款]超时未拼团成功，自动结算处理{}",promGroup.getId());
                settleSingleGroup(promGroup);
            }
            promGroupMapper.closePromGroup(promGroups);
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error("自动结算错误:{}",e);
            transactionManager.rollback(transactionStatus);
        }
    }



    /**
     * 单笔结算处理
     * @param promGroup
     */
    private void settleSingleGroup(PromGroup promGroup) {
        List<PromGroupDetail> promGroupDetails=promGroupDetailMapper.selectByGroupNo(promGroup.getGroupNo());
        DivideAppyPo divideAppyPo=new DivideAppyPo();
        divideAppyPo.setGroupNo(promGroup.getGroupNo());
        List<DivideDetailPo> divideDetailPos=new ArrayList();
        long existsHitFlagNum=promGroupDetails.stream().filter(o->o.getHitFlag()==1).count();
        for(PromGroupDetail promGroupDetail:promGroupDetails){
            int hitFlag=promGroupDetail.getHitFlag();
            if(1==hitFlag){
               //统计待分润金额
                divideAppyPo.setPaySeqNo(promGroupDetail.getPaySeqNo());
                divideAppyPo.setPayAmt(promGroupDetail.getPayAmt());
                divideAppyPo.setProfitRate(promGroupDetail.getProfitRate());
                promGroupDetail.setActReturnAmt(BigDecimal.ZERO);
            }else {
                //构造分账明细
                DivideDetailPo divideDetailPo=new DivideDetailPo();
                divideDetailPo.setDivideId(promGroupDetail.getId());
                divideDetailPo.setRecvUserNo(promGroupDetail.getBuylerId());
                divideDetailPo.setRecvAmt(promGroupDetail.getReturnAmt().multiply(new BigDecimal(100)).intValue());
                divideDetailPos.add(divideDetailPo);
                if(StringUtils.isNotEmpty(promGroupDetail.getPaySeqNo())){
                    logger.info("开始对：{}发起自动退款操作",promGroupDetail.getOrderNo());
                    //发起退款申请
                    refundService.autoRefund(promGroupDetail.getOrderNo(),promGroupDetail.getPayAmt());
                    //todo  退款失败 需要继续处理 需要放到job里去执行
                    if(existsHitFlagNum>=1){//存在命中人员
                        promGroupDetail.setActReturnAmt(promGroupDetail.getReturnAmt());
                        //对团员进行补偿,计入余额
                        TbAccountInfo tbAccountInfo= accountInfoService.saveUserAccount(promGroupDetail.getBuylerId(),AccountTypeEnum.BONUS_ACCOUNT);
                        AccountAmtOperDto accountAmtOperDto=new AccountAmtOperDto();
                        accountAmtOperDto.setSourceTradeType(TradeTypeEnum.ACQUIRE_BONUS);
                        accountAmtOperDto.setTradeAmt(promGroupDetail.getReturnAmt());
                        accountAmtOperDto.setSourceOrderNo(promGroup.getGroupNo());
                        accountAmtOperDto.setAccoutNo(tbAccountInfo.getAccountNo());
                        accountSerivce.operAccountAmt(accountAmtOperDto);
                    }
                }
            }
            //更新团购结算信息
            promGroupDetail.setSettleTime(new Date());
            promGroupDetail.setSettleStatus(SettleStatusEnum.SETTLE.getCode());
            promGroupDetailMapper.updateByPrimaryKeySelective(promGroupDetail);
        }
        //发起分账请求
        divideAppyPo.setDivideDetailPoList(divideDetailPos);
        if(existsHitFlagNum>=1) {//存在命中人员
            logger.info("对团购{},发起自动自动分账操作",promGroup.getGroupNo());
            profitDetailService.applyDivide(divideAppyPo);
            // 对团长自动计算分润 并计入余额
            BigDecimal profitAmt = divideAppyPo.getProfitRate().divide(new BigDecimal("100")).multiply(divideAppyPo.getPayAmt());
            promGroup.setProfitAmt(profitAmt);
            promGroupMapper.updateByPrimaryKey(promGroup);
            TbAccountInfo tbAccountInfo = accountInfoService.saveUserAccount(promGroup.getLeaderUser(), AccountTypeEnum.CASH_ACCOUNT);
            AccountAmtOperDto accountAmtOperDto = new AccountAmtOperDto();
            accountAmtOperDto.setSourceTradeType(TradeTypeEnum.GROUP_BONUS);
            accountAmtOperDto.setTradeAmt(profitAmt);
            accountAmtOperDto.setSourceOrderNo(promGroup.getGroupNo());
            accountAmtOperDto.setAccoutNo(tbAccountInfo.getAccountNo());
            accountSerivce.operAccountAmt(accountAmtOperDto);
        }
    }

    @Override
    public void createPromGroupDetail(String groupNo,TbOrderTotal tbOrderTotal, List<TbOrderDetail> tbOrderDetails) {
        //检查是否有效
        checkJoinGroup(groupNo,tbOrderTotal.getBuylerId());
        PromGroupDetail promGroupDetail1=new PromGroupDetail();
        promGroupDetail1.setOrderNo(tbOrderTotal.getOrderNo());
        promGroupDetail1.setBuylerId(tbOrderTotal.getBuylerId());
        promGroupDetail1.setGroupNo(groupNo);
        TbOrderDetail tbOrderDetail=tbOrderDetails.get(0);
        promGroupDetail1.setItemNo(tbOrderDetail.getItemNo());
        promGroupDetail1.setStockNo(tbOrderDetail.getStockNo());
        promGroupDetail1.setOrderAmt(tbOrderTotal.getActOrderAmt());
        //团员返还比例
        TbItemSku tbItemSku=tbItemSkuMapper.selectByStockNo(promGroupDetail1.getStockNo());
        promGroupDetail1.setReturnAmt(tbOrderTotal.getOrderAmt().multiply(tbItemSku.getReturnRate()).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_DOWN));
        //团长利润
        promGroupDetail1.setProfitRate(tbItemSku.getScorePercent());
        promGroupDetail1.setCreateNo(tbOrderTotal.getBuylerId());
        promGroupDetail1.setCreateTime(new Date());
        promGroupDetailMapper.insertSelective(promGroupDetail1);
    }


}
